#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import paramiko
from util import Properties, Linux, Windows, Mail, joinPath
import time


class AccountRecovery:
    scriptIp = '172.16.1.64'
    pkey = 'zhangfan_id_rsa'
    key = paramiko.RSAKey.from_private_key_file(pkey, password='')  # 有解密密码时,
    prop = Properties('a.properties')
    username = 'root'
    password = '123456'
    scriptDir = '/work/script'
    genFile = 'bpAccountRecover.sql'
    dstDir = 'sql_update/inst'

    def __init__(self):
        self._ip = self.prop.get('ip')
        self._pid = self.prop.get('playerid')
        self._dbFileName = self.prop.get('dbFileName')
        if self._dbFileName is None:
            raise Exception
        print(self.prop.properties)
        self._linux = Linux()
        self._win = Windows()
        self._mail = Mail('mailTemplate.html')

    def runRemoteRecoveryScript(self):
        command = "cd /work/script; sh accountRecovery.sh %s %s %s" % (self._pid, self._ip, self._dbFileName)
        print('command: %s' % command)

        sshClient = self._linux.getSShConByPassword(self.scriptIp, 22, self.username, self.password)
        stdin, stdout, stderr = sshClient.exec_command(command)
        if stderr.readable():
            print(stderr.read().decode('utf-8'))
        if stdout.readable():
            print(stdout.read().decode('utf-8'))
        if stdin.readable():
            print(stdin.read().decode('utf-8'))

    def remote_scp(self):
        localPath = self.prop.get('localDir', '.')
        return self._linux.remote_scp(self.scriptIp, 22, self.scriptDir, localPath, self.genFile, self.username, self.password)

    def fileSize(self):
        return self._win.fileSize(self.genFile)

    def mkdir(self):
        return self._win.mkdir(self.dstDir, True)

    def zipdir(self):
        return self._win.zip('sql_update')

    def copyFile2Dir(self):
        self._win.cpFile(self.genFile, joinPath(self.dstDir, 'inst.sql'))

    def mailReplace(self, fileSize, zipFileMD5, zipFileName):
        content = self._mail.readTemplate()
        zipPath = joinPath(zipFileName.split('.')[0], zipFileName)

        sender = self.prop.get('sender', '张帆')
        updateContent = self.prop.get('updateContent', 'ERROR!!!需要填写')
        updateServer = self.prop.get('updateServer', 'ERROR!!!需要填写')

        content = content.replace('${sender}',sender).replace('${updateServer}', updateServer).replace('${updateContent}', updateContent)
        date = time.strftime('%Y.%m.%d', time.localtime())
        content = content.replace('${date}', date).replace('${zipFileName}', zipPath)
        ret = content.replace('${fileSize}', str(fileSize)).replace('${zipFileMD5}', zipFileMD5)
        return ret

    def ftp_upload(self, zipFileName):
        uploadDir = r"""\\172.16.1.92\badperson_server\guofu\gengxin"""
        self._win.mkdir(zipFileName.split('.')[0], True, uploadDir)  # 构造目录

        desDirPath = joinPath(uploadDir, zipFileName.split('.')[0])
        desDirPath = desDirPath.replace('/', '\\')  # 得到全部路径
        self._win.ftp_upload(desDirPath, zipFileName)  # 上传文件

    def run(self):
        self.runRemoteRecoveryScript()  # 运行accountRecovery.sh
        genSqlPath = 'bpAccountRecover.sql'
        genSqlPath = self.remote_scp()  # 取回生成后的文件

        fileSize = self.fileSize()
        print('fileSize:%s' % fileSize)
        self.mkdir()  # 构建准备压缩的目录
        self.copyFile2Dir()  # copy sql到压缩目录
        zipFileName = self.zipdir()  # 将目录压缩成zip
        zipFileMD5 = self._win.MD5(zipFileName)  # 得到zip的MD5

        # 替换邮件内容
        mailContent = self.mailReplace(fileSize, zipFileMD5, zipFileName)
        self._mail.show(mailContent)

        # 上传到ftp
        self.ftp_upload(zipFileName)


def test():
    ar = AccountRecovery()
    ar.run()


if __name__ == '__main__':
    test()
